cmake_minimum_required(VERSION 3.17)
project(ExampleToReference3rdLibs)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/module)

set(ALL_TARGETS_NAME
    cjson
    z
)
set(EACH_TARGET_VERSION
    v1.7.17
    1.2.13
)
# only cmake 3.17 and above support the usage of "foreach IN ZIP_LISTS", user can use "foreach(nameItem ALL_TARGETS_NAME)" to replace
foreach (nameItem versionItem IN ZIP_LISTS ALL_TARGETS_NAME EACH_TARGET_VERSION)
    find_package(${nameItem} REQUIRED)
    if (${nameItem}_FOUND)
        list(APPEND FOUND_TARGETS_DIR ${${nameItem}_INCLUDE_DIR})
        list(APPEND FOUND_TARGETS_LIBS ${${nameItem}_LIBRARY})
    endif ()
endforeach ()

list(LENGTH ALL_TARGETS_NAME srcLibLen)
list(LENGTH FOUND_TARGETS_LIBS foundLibLen)

add_executable(ExcuteReference main.cpp)
# 根据查询到的缓存结果判断是否需要利用缓存
if (NOT srcLibLen EQUAL foundLibLen) 
    add_dependencies(ExcuteReference cjson z)
    message(info, "project dependence 3rd-party build")
    set(ALL_INCLUDE_DIR
        ${CMAKE_CURRENT_SOURCE_DIR}/third_party/cjson/include
        ${CMAKE_CURRENT_SOURCE_DIR}/third_party/z/include    
    )
    set(ALL_LIBS
        ${CMAKE_CURRENT_SOURCE_DIR}/third_party/cjson/lib64/libcjson.so
        ${CMAKE_CURRENT_SOURCE_DIR}/third_party/z/lib/libz.so
    )
else ()
    set(ALL_INCLUDE_DIR ${FOUND_TARGETS_DIR})
    set(ALL_LIBS ${FOUND_TARGETS_LIBS})
endif ()

target_include_directories(ExcuteReference PRIVATE ${ALL_INCLUDE_DIR})
target_link_libraries(ExcuteReference ${ALL_LIBS})